package niuke;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lj
 * @Description: 二叉树的层次遍历-按层
 * @date 2020-10-27 15:03
 * @QQ 851477108
 */


public class erchashu2 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    public List<List<Integer>> levelOrder (TreeNode root) {
        //按层遍历即可
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null){
            return lists;
        }

        List<TreeNode> nodes = new ArrayList<>();
        nodes.add(root);
        while (!nodes.isEmpty()){
            int size = nodes.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode remove = nodes.remove(0);
                list.add(remove.val);
                if (remove.left != null){
                    nodes.add(remove.left);
                }
                if (remove.right != null){
                    nodes.add(remove.right);
                }
            }
            lists.add(list);
        }
        return lists;
    }
}
